package com.example.demo.restTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class RestUtil {


    /*
     JSONObject content = new JSONObject();//放入body中的json参数
     content.put("mode","delete");
     content.put("name",queue);
     content.put("vhost","/" + vhost);
     */


    @Autowired
    RestTemplate restTemplate;


    public String postObjectByJson(String url, String json) {
        //Object obj=null;
        //String json=JSONUtil.poToJson(obj);
        HttpEntity<String> formEntity = null;
        String result = null;
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        formEntity = (json == null) ? new HttpEntity<String>(headers) : new HttpEntity<String>(json, headers);
        try {
            result = restTemplate.postForObject(url, formEntity, String.class);
        } catch (Exception e) {
            //服务调用报错日志
        }

        return result;
    }

    public String postEnityByJson(String url, String json) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String str = null;
        HttpEntity<String> formEntity = null;
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        formEntity = (json == null) ? new HttpEntity<>(headers) : new HttpEntity<String>(json, headers);
        ResponseEntity<String> result = null;
        HttpStatus status = null;
        try {
            result = restTemplate.postForEntity(url, formEntity, String.class);
            status = result.getStatusCode();//获取返回状态
            if (status.is2xxSuccessful()) {
                if (result.hasBody())
                    str = result.getBody();
                else {
                    //服务失败日志
                }
            } else {
                //服务失败日志
            }
        } catch (Exception e) {
            //服务调用报错日志
        }
        return str;
    }

    public String getEnity(String url, Map<String, String> map) {
        String finalUrl = url;
        String result = null;
        if (!(map == null || map.size() == 0)) {
            StringBuilder sr = new StringBuilder(url);
            sr.append("?");
            for (String key : map.keySet()) {
                sr.append(key + "=" + "{" + key + "}" + "&");
            }
            result = restTemplate.getForObject(sr.toString().substring(0, sr.length() - 1), String.class, map);
        } else
            result = restTemplate.getForObject(finalUrl, String.class);
        return result;

    }
}
